Last week, we talked about some convenient functions in Java. Here is a library which is a mother of all convenient functions. I met Google Guava about 2-3 years ago when I was working on MAWA Analyzer project and I have been staying a huge fan of it. Guava is a well-designed API which is meant to simplify your coding by introducing functions related to Collections, Functional Programming, Concurrency, Ordering, String Manipulations, IO Utilities, Reflection Utils, etc. Codes were advised and reviewed by Joshua Bloch, the author of Effective Java, which follows many of the patterns in the book such as the static factory, builder, immutability, null-checks, etc. Guava was open sourced as early as in 2007. The API uses Java Generics as Java 5 was already available at the time. Guava just makes the coding super exciting and fun!
Google Guava version 20.0 is out on October 28, 2016. See here to resolve dependency via Maven or Gradle. The listed items below are from Guava which I find convenient often times. They are mostly, if not all, supported in version 19.0 and up. In case you are still unsure on their usage, refer to their Java Doc. I strongly recommend at least have a look at their API doc. They just have so many functions I won’t be able to cover them all here. The functions introduced below are the ones I use and found themselves useful.
This item is probably what made Guava famous. You can name a data structure to define using their static factory methods. There are ways to define structures:
Note: if the list is immutable, consider ImmutableList.reverse() instead.
Returns a view of the underlying list, partitioned into chunks of the specified size.
remove all null values from a collection
create immutable List directly
create immutable List from a standard collection
Using above copy using builder
Sets support intersection as follows,
Sets also support cartesianProduct or powerSet function, {: style=”margin-bottom: .5em; margin-top: 1em;”}yy
create immutable Set directly
create immutable Set from a standard collection
Using above copy using builder
difference:
create immutable Map directly
create immutable Map from a standard collection
Using above copy using builder
SortedMap:
Ordering is Guava’s “fluent” Comparator class, which can be used to build complex comparators and apply them to collections of objects. It’s basically a “comparator” instance. Examples are below:
natural()
usingtoString()
Sort then Binary Search
find min/max without sort
Chaining 2 orderings
nulls first
Until now, Strings are usually handled by company’s own implementation of “StringUtils”. This is typically a bad idea as there are libraries out there that handle most of the job. Trust these libraries for 2 main reasons. First, hundreds of people have laid their eyes on the codes online (open-sourced libraries). Second, a lot of people are using them. There are other options for StringUtils than Guava. There is Apache Commons. The project started n 2002. Somewhat Old. Still, has quite useful libraries. I love their StringBuilder/StringWriter functions. Guava has their lovely ones too such as Joiner, Splitter and especially CharMatcher. See below:
Joiner:
Or you can just straight apply,
Splitter:
CharMatcher, this is my favourite, I felt like writing a poem when I first used it:
You can run one of the following functions,
Charsets:
Your traditional compareTo method might look like this:
1
2
3
4
5
6
7
8
9
10
11
@Override
public int compareTo(User that) {
int result = 0;
result = userId != null ? userId.compareTo(that.getUserId()) : result;
result = result == 0 ? personName.compareTo(that.getPersonName()) : result;
result = result == 0 ? age.compareTo(that.getAge()) : result;
result = result == 0 ? address.compareTo(that.getAddress()) : result;
return result;
}
Now, above can be shortened using Guava like this.
1
2
3
4
5
6
7
8
public int compareTo(User that) {
return ComparisonChain.start()
.compare(userId, that.getUserId())
.compare(personName, that.getPersonName(), Ordering.natural().nullsFirst())
.compare(age, that.getAge(), Ordering.natural().nullsFirst())
.compare(address, that.getAddress())
.result();
}
Look how clean it is. It’s also just beautiful that you can apply Ordering in this chain. Ordering is basically used as a comparator.
Don’t use your own Utils functions. Use only ones applicable specific to your project. There are many other options for Utils. However, at least for Java, Big 2 Java Collections Library is, Apache Commons and Google Guava. These libraries use names very well made usage so much easier and fun. There will be a time where you can solve your issues using one of these libraries, trust me Make sure you check them first and see if you can incorporate these libraries into your project. Also, please check out my github for test cases on Guava library. I have mostly covered examples I discussed in this blog. I may have added one or two more than what has covered here actually hehe